//
//  Lock_OC_DemoVC.m
//  APSwift
//
//  Created by jianbo.pei on 2024/1/12.
//

#import "Lock_OC_DemoVC.h"
#import <os/lock.h>
#import <pthread/pthread.h>

@interface Lock_OC_DemoVC ()

@property (nonatomic, assign) int iCount;
@property (nonatomic, assign) os_unfair_lock iUnfairLock;
@property (nonatomic, strong) NSLock *iLock;
@property (nonatomic, strong) NSCondition *iCondition;
@property (nonatomic, strong) NSConditionLock *iConditionLock;
@property (nonatomic, strong) NSRecursiveLock *iRecursiveLock;
@property (nonatomic, strong) dispatch_queue_t iQueue;
@property (nonatomic, strong) NSMutableDictionary *dataDict;

@end

@implementation Lock_OC_DemoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    NSLog(@"Hello");
    
    self.iCount = 50;
    
    self.iUnfairLock = OS_UNFAIR_LOCK_INIT;
    
    self.iLock = [[NSLock alloc] init];
    
    self.iCondition = [[NSCondition alloc] init];
    
    self.iConditionLock = [[NSConditionLock alloc] init];
    
    self.iRecursiveLock = [[NSRecursiveLock alloc] init];
    
    self.iQueue = dispatch_queue_create("ap", DISPATCH_QUEUE_CONCURRENT);
    
    self.dataDict = [[NSMutableDictionary alloc] init];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self test];
}

- (void)test 
{
    for (int i = 0; i < 10; i++) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            self.iCount--;
            
            /// 等价于
//            self.iCount = self.iCount + 1;
            
            /// 也等价于
            int oldValue = self.iCount;
            int newValue = oldValue + 1;
            self.iCount = newValue;
            
            NSLog(@"%s, iCount is %d", __func__, self.iCount);
        });
    }
}

/** 我们期望的结果是：49、48、47、46、45、44、43、42、41
 
 /// 1
 Hello
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 48
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 47
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 49
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 46
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 44
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 45
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 40
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 42
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 41
 -[Lock_OC_DemoVC test]_block_invoke, iCount is 43
 
 */


@end
